package com.geek.factory.security;

import cn.hutool.json.JSONUtil;
import com.geek.factory.constant.MessageConstant;
import com.geek.factory.constant.RedisTokenConstant;
import com.geek.factory.entity.User;
import com.geek.factory.exception.AccessTokenInvalidException;
import com.geek.factory.exception.FactoryException;
import com.geek.factory.utils.JwtHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * TODO
 *
 * @author chemin
 * @since 2025/7/7
 *
 * 注意：
 * Spring Security本身已经提供了一套完整的认证和授权机制，包括拦截请求、检查用户是否登录、验证用户权限等功能。在这种情况下，通常不需要再额外配置LoginInterceptor。
 * 因为Spring Security的过滤器链（如UsernamePasswordAuthenticationFilter、ExceptionTranslationFilter等）已经能够很好地处理这些逻辑。
 * 若在用户登录后，记录用户的访问路径、访问时间等信息，以便进行后续的数据分析，可以再新增LoginInterceptor进行处理。
 *
 * 作用：解析请求头中的token，并验证合法性
 * 继承 OncePerRequestFilter 保证请求经过过滤器一次
 *
 */
@Slf4j
@RequiredArgsConstructor
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter{

    private final RedisTemplate<String,Object> redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //1.直接放行登陆操作
        String uri = request.getRequestURI();
        if(uri.contains("/login") ||
                uri.contains("/auth") ||
                uri.contains("/sms/**") ||
                uri.contains("/api/ams/**") ||
                uri.contains("/t_contract/**") ||
                uri.contains("/purchase-order/status-stats")||
                uri.contains("/orders/uninvoiced/count")
        ){
            //直接放行
            filterChain.doFilter(request,response);
            return;
        }


        //2.从请求头中获取token数据
        String authorization = request.getHeader("Authorization");
        if(StringUtils.isEmpty(authorization)){
            //直接放行  401 403
            filterChain.doFilter(request,response);
            return;
        }
        String token = authorization.substring(7);
        log.info("JwtAuthenticationTokenFilter preHandle ~ token = "+token);

        //3.验证其是否过期
        if(JwtHelper.isExpiration(token)){
            throw new AccessTokenInvalidException(MessageConstant.ACCESS_TOKEN_VERIFY_FAIL);
        }

        //4.验证token的合法性
        Long userId = JwtHelper.getUserId(token);
        if(userId == null){
            throw new AccessTokenInvalidException(MessageConstant.TOKEN_ILLEGAL);
        }

        //5.从redis中获取用户信息  user::token::1
        Object o = redisTemplate.opsForValue().get(RedisTokenConstant.USER_TOKEN+"::"+userId);
        if(o==null){
            throw new FactoryException(MessageConstant.TOKEN_REDIS_NULL);
        }
        User user = JSONUtil.toBean(o.toString(), User.class);

        //5.将Authentication对象（用户信息、已认证状态、权限信息）存入 SecurityContextHolder
        LoginUser loginUser = new LoginUser(user);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser , null , loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //放行
        filterChain.doFilter(request , response);
    }

}
